import { TemplateDef } from "@/api";
import { createAtom, useStore } from "@/util/hooks";
import { Form, Input } from "@arco-design/web-react";
import { useEffect } from "react";
import { TemplateFileFormProps, TemplateFileFormStore } from "./inteface";

export const TemplateFileFormAtom = createAtom<TemplateFileFormStore>({
  requestFormUpdate: false,
});

export const TemplateFileForm = ({
  height,
  ...props
}: TemplateFileFormProps) => {
  const [form] = Form.useForm();
  const formStore = useStore(TemplateFileFormAtom);

  function onValuesChange(value: Partial<any>, values: Partial<any>) {
    const newValues = values as TemplateDef;
    formStore.updateStoreAll((prev) => {
      const data = prev.data;
      const newData = { ...data, ...newValues };
      return { ...prev, data: newData };
    });
  }

  const requestFormUpdate = formStore.value.requestFormUpdate;

  useEffect(() => {
    if (!requestFormUpdate) return;
    const data = formStore.value.data;
    formStore.updateStore({
      requestFormUpdate: false,
    });
    form.setFieldsValue(data);
  }, [requestFormUpdate]);

  return (
    <>
      <Form
        form={form}
        onValuesChange={onValuesChange}
        layout="vertical"
        style={{ width: "auto", padding: 16, height: height }}
        {...props}
      >
        <Form.Item
          label="代码相对根目录模版"
          field="codeBaseUrlTemp"
          requiredSymbol={false}
          rules={[{ required: false }]}
        >
          <Input placeholder="src/main/java" />
        </Form.Item>
        <Form.Item
          label="包名模版"
          field="packageNameTemp"
          requiredSymbol={false}
          rules={[{ required: false }]}
        >
          <Input placeholder="com.example.biz.entity" />
        </Form.Item>
        <Form.Item
          label="文件名模版"
          field="fileNameTemp"
          requiredSymbol={false}
          rules={[{ required: false }]}
        >
          <Input placeholder="${EntityName}.java" />
        </Form.Item>
      </Form>
    </>
  );
};
